package com.zyw.module.console.admin.auth;

import com.zyw.module.console.user.po.User;
import com.zyw.module.console.user.service.UserService;
import com.zyw.security.shiro.web.authc.AuthInfo;
import com.zyw.security.shiro.web.authc.AuthService;
import com.zyw.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhangyw
 * @date 2018/1/25 10:59
 */
@Service
public class FormAuthService implements AuthService {

    @Autowired
    private UserService userService;

    @Override
    public String getCredentials(Object principal) {
        return userService.getPassword((String) principal);
    }

    @Override
    public AuthInfo getAuthInfo(Object principal) {
        List<User> users = userService.findByUsername((String) principal);
        if (users != null && !users.isEmpty()) {
            AuthInfo authInfo = new AuthInfo();
            User user = users.get(0);
            authInfo.setUserid(user.getId());
            authInfo.setUsername(user.getUsername());
            authInfo.setPassword(user.getPassword());
            authInfo.setStatus(user.getStatus());
            return authInfo;
        }

        return null;
    }

    @Override
    public boolean validCredentials(String principal, String targetCredentials, String sourceCredentials) {
        return StringUtils.equals(targetCredentials, sourceCredentials);
    }
}
